﻿using System;
using System.Web;
using System.Web.Routing;
using System.Web.SessionState;
using StackExchange.Profiling;

namespace MiniProfilerWebFormsEnabler
{
   
        public class MiniProfilerHttpHandler : IHttpHandler, IRequiresSessionState
        {

            public MiniProfilerHttpHandler()
            {

            }

            private RequestContext requestContext;
            public MiniProfilerHttpHandler(RequestContext requestContext)
            {
                this.requestContext = requestContext;
            }

            public bool IsReusable
            {
                get { return false; }
            }
            
            public const string MINI_PROFILER_ENABLED_SESSION_KEY = "MiniProfilerEnabled";

            public void ProcessRequest(HttpContext context)
            {
                bool enabled = (bool)context.Items[MiniProfilerRouteHandler.ENABLED_KEY];
                if (context.Session != null)
                {
                    context.Session[MINI_PROFILER_ENABLED_SESSION_KEY] = enabled;

                    context.Response.Write("<html><body>MiniProfiler Enabled For Your Session Set To: " + enabled.ToString() + ".<BR /><BR />" +
                        "Change to <A href=\"" + (!enabled).ToString() + "\">Enabled = \"" +
                        (!enabled).ToString() + "</a>");
                    if (enabled)
                    {
                        if (MiniProfiler.Current == null)
                        {
                            MiniProfiler.Start();
                        }
                    }
                    context.Response.Write(MiniProfiler.RenderIncludes(RenderPosition.Right).ToHtmlString() + "\"</body></html>");
                }
                
                MiniProfiler.Stop();
            }
        }
  
}
